import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/bean/bean_login.dart';
import 'package:flutter_learn_vi/src/bean/bean_mine.dart';
import 'package:flutter_learn_vi/src/bean/bean_user.dart';
import 'package:flutter_learn_vi/src/common/user_helper.dart';
import 'package:flutter_learn_vi/src/net/dio_utils.dart';
import 'package:flutter_learn_vi/src/utils/base64_utils.dart';
import 'package:flutter_learn_vi/src/utils/log_util.dart';
import 'package:flutter_learn_vi/src/utils/toast_utils.dart';
import 'dart:convert' as convert;

/// 创建人： Created by zhaolong
/// 创建时间：Created by  on 2021/1/26.
///
/// 可关注公众号：我的大前端生涯   获取最新技术分享
/// 可关注网易云课堂：https://study.163.com/instructor/1021406098.htm
/// 可关注博客：https://blog.csdn.net/zl18603543572
///
/// 代码清单
/// 登录功能封装
class LoginModel {
  Future<void> submit(
      String userName, String password, BuildContext context) async {
    //校验
    checkUserName(userName);
    checkPassword(password);

    //参数封装
    Map<String, String> map = new Map();
    map["username"] = userName;
    map["password"] = password;

    Map<String, dynamic> map2 = new Map();
    String jsonString = convert.jsonEncode(map);
    map2["login"] = Base64Util.base64Encode("A$jsonString");

    //post请求发送
    ResponseInfo responseInfo = await DioUtils.instance.postRequest(
      url: HttpHelper.UWER_LOGIN_V2_URL,
      jsonMap: map2,
    );
    //登录成功
    if (responseInfo.success) {
      if (responseInfo.data is List) {
        List list = responseInfo.data;
        if (list.length == 1) {
          //解析用户数据
          LoginBean loginBean = LoginBean.fromJson(list[0]);
          goHome(loginBean.user, password, context);
        } else {
          List<UserBean> userList = [];
          list.forEach((element) {
            userList.add(UserBean.fromJson(element));
          });

          ///有多个用户
          UserBean userBean = await selectUserBeanFunction(userList, context);
          goHome(userBean, password, context);
        }
      } else {
        //解析用户数据
        UserBean userBean = UserBean.fromJson(responseInfo.data);
        goHome(userBean, password, context);
      }
    } else {
      //登录失败
      ToastUtils.showToast(responseInfo.message);
    }
  }

  ///[loginType]
  /// 1 手机号
  /// 2 员工号
  /// 3 身份证号
  /// 4 账号
  Future<bool> submitV3(String userName, String password, int loginType,
      BuildContext context) async {
    //校验
    checkUserName(userName);
    checkPassword(password);

    //参数封装
    Map<String, dynamic> map = new Map();
    map["username"] = userName;
    map["password"] = password;
    map["loginType"] = loginType;

    Map<String, dynamic> map2 = new Map();
    String jsonString = convert.jsonEncode(map);
    map2["login"] = Base64Util.base64Encode("A$jsonString");

    //post请求发送
    ResponseInfo responseInfo = await DioUtils.instance.postRequest(
      url: HttpHelper.UWER_LOGIN_V4_URL,
      jsonMap: map2,
    );
    //登录成功
    if (responseInfo.success) {
      if (responseInfo.data is List) {
        List list = responseInfo.data;
        if (list.length == 1) {
          //解析用户数据
          LoginBean loginBean = LoginBean.fromJson(list[0]);
          goHome(loginBean.user, password, context, loginType: loginType);
        } else {
          List<UserBean> userList = [];
          list.forEach((element) {
            userList.add(UserBean.fromJson(element));
          });

          ///有多个用户
          UserBean userBean = await selectUserBeanFunction(userList, context);
          goHome(userBean, password, context, loginType: loginType);
        }
      } else {
        //解析用户数据
        UserBean userBean = UserBean.fromJson(responseInfo.data);
        goHome(userBean, password, context, loginType: loginType);
      }
      return true;
    } else {
      //登录失败
      ToastUtils.showToast(responseInfo.message);
      return false;
    }
  }

  void goHome(UserBean userBean, String password, BuildContext context,
      {int loginType = 1}) async {
    Map<String, dynamic> map = Map();
    map["username"] = userBean.username;
    map["password"] = password;
    if (loginType == 2) {
      //"标识 0密码登录  1员工号登录"
      map["flag"] = "1";
    } else {
      //"标识 0密码登录  1员工号登录"
      map["flag"] = "0";
    }

    Map<String, dynamic> map2 = new Map();
    String jsonString = convert.jsonEncode(map);
    map2["login"] = Base64Util.base64Encode("A$jsonString");

    ResponseInfo responseInfo = await DioUtils.instance.postRequest(
      url: HttpHelper.UWER_LOGIN_V2_URL,
      jsonMap: map2,
    );
    LoginBean loginBean;
    //登录成功
    if (responseInfo.success) {
      List list = responseInfo.data;
      loginBean = LoginBean.fromJson(list[0]);
      userBean = loginBean.user;
    } else {
      ToastUtils.showToast(responseInfo.message);
      return;
    }
    UserHelper.getInstance.loginBean = loginBean;
    //保存本地标识
    UserHelper.getInstance.setUserBean(userBean);
    ResponseInfo mineResponse = await DioUtils.instance.getRequest(
      url: HttpHelper.sysmineimg + userBean.mineId.toString(),
    );
    //矿成功
    if (mineResponse.success) {
      MineBean mineBean = MineBean.fromJson(mineResponse.data);
      UserHelper.getInstance.mineBean = mineBean;
      //保存本地标识
      UserHelper.getInstance.setUserBean(userBean);
    } else {
      LogUtils.e("获取矿信息失败");
      ToastUtils.showToast("获取矿信息失败");
      return;
    }

    UserHelper.getInstance.goHomePage(context);
  }

  void checkPassword(String value) {
    if (value.trim().length == 0) {
      ToastUtils.showToast("请输入密码");
      return;
    }
  }

  void checkUserName(String value) {
    if (value.trim().length == 0) {
      ToastUtils.showToast("请输入用户账号");
      return;
    }
  }

  Future<UserBean> selectUserBeanFunction(
      List<UserBean> userList, BuildContext context) async {
    return showDialog(
        context: context,
        barrierDismissible: true,
        builder: (BuildContext context) {
          return AlertDialog(
            content: Container(
              height: 200,
              width: MediaQuery.of(context).size.width,
              child: ListView.builder(
                itemBuilder: (BuildContext context, int index) {
                  UserBean userBean = userList[index];
                  return ListTile(
                    title: Text(userBean.mineName),
                    onTap: () {
                      Navigator.of(context).pop(userBean);
                    },
                  );
                },
                itemCount: userList.length,
              ),
            ),
          );
        });
  }
}
